/**
 * @title ListScoreAdapter.java
 * @package com.esun.cheetah.view.match.matchlist.adapter
 * @description 比赛列表中的比赛项对应的Adapter
 * @author liugan
 * @date 2012-7-31
 * @copyright 深圳市易讯天空
 */
package com.esun.cheetah.view.match.matchlist.adapter;

import java.util.ArrayList;

import com.esun.cheetah.R;
import com.esun.cheetah.biz.match.matchlist.MatchListManager;
import com.esun.cheetah.biz.personal.attention.AddAttentionMatch;
import com.esun.cheetah.biz.personal.attention.CancelAttenMatch;
import com.esun.cheetah.config.Config;
import com.esun.cheetah.model.match.matchlist.Match;
import com.esun.cheetah.model.match.matchlist.Match.MatchState;
import com.esun.cheetah.view.match.matchlist.ScoreActivity;
import com.esun.util.log.EDebug;
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @title OneDayMatchAdapter
 * @description 比赛列表中的比赛项对应的Adapter
 * @author liugan
 */
public class OneDayMatchAdapter extends BaseAdapter{
	/**
	 * @field attentionIsDoing
	 * @description 标识是否正在请求关注。正在请求时，将不响应用户的点击事件。
	 */
	private static boolean attentionIsDoing;

	/**
	 * @field markView
	 * @description 用户点击了的ImageView
	 */
	public static ImageView markView;

	/**
	 * @field matchInfo
	 * @description 相关的比赛信息，指向缓存的引用
	 */
	protected Context context;

	/**
	 * @field markHandler
	 * @description 处理请求关注的handler
	 */
	protected Handler mAttentionHandler =  new AttentionHandler();

	/**
	 * @field markHandler
	 * @description 处理取消关注的handler
	 */
	protected Handler mCancelAttentionHandler = new CancelAttentionHandler();
	
	private Resources mResources;

	/**
	 * @param activity
	 */
	public OneDayMatchAdapter(FragmentActivity activity) {
		this.context = activity;
		mResources = context.getResources();
	}

	@Override
	public int getCount() {
		if (getList() == null) {
			return 0;
		}
		return getList().size();
	}

	@Override
	public long getItemId(int position) {
		return 0;
	}

	/**
	 * @title MarkHandler
	 * @description 请求关注比赛的Handler类
	 * @author liugan
	 */
	private class AttentionHandler extends Handler {

		@Override
		public void handleMessage(Message msg) {
			attentionIsDoing = false;
			if (msg.what == Config.COMMON_INFO_MSG_20001) {
				
				Match match = (Match)msg.obj;
				if(match != null){
					match.setMarked(true);
					MatchListManager.getInstance().attentioned(match);
				}
				
				((ScoreActivity)context).updateMatchesCount();
				((ScoreActivity)context).updateMatchesList();
				Toast.makeText(context, "关注成功", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(context, "关注失败", Toast.LENGTH_SHORT).show();
			}
			super.handleMessage(msg);
		}

	}

	/**
	 * @title CancelMarkHandler
	 * @description 请求取消关注的handler类
	 * @author liugan
	 */
	private class CancelAttentionHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			attentionIsDoing = false;
			if (msg.what == Config.COMMUNICATER_SUCCESS) {
				// 更新本地关注列表
				Match match = (Match)msg.obj;
				
				if(match != null){
					match.setMarked(false);
					MatchListManager.getInstance().cancelAttentioned(match);
				}
				
				((ScoreActivity)context).updateMatchesCount();
				((ScoreActivity)context).updateMatchesList();
				
				Toast.makeText(context, "取消成功", Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(context, "取消失败", Toast.LENGTH_SHORT).show();
			}
			super.handleMessage(msg);
		}

	}

	private class OnMarkButtonClickListener implements View.OnClickListener {
		Match info;

		public OnMarkButtonClickListener(Match info) {
			this.info = info;
		}

		@Override
		public void onClick(View v) {
			
			if(info.isMarked()){
				asyncCancelAttention(info);
			}else{
				asyncAttention(info);
			}
			ScoreActivity activity = (ScoreActivity)context;
			activity.updateMatchesList();
			activity.updateMatchesCount();
			

		}

		/**
		 * @title asyncAttention
		 * @description 异步关注
		 * @param match
		 */
		private void asyncAttention(Match match) {
			AddAttentionMatch addAttentionMatch = new AddAttentionMatch(mAttentionHandler,match, Config.JINGCAIZUQIU);
			addAttentionMatch.startCommunicate();
			
		}

		/**
		 * @title asyncCancelAttention
		 * @description 异步取消关注
		 * @param match
		 */
		private void asyncCancelAttention(Match match) {
			CancelAttenMatch cancelAttenMatch = new CancelAttenMatch(mCancelAttentionHandler,match);
			cancelAttenMatch.startCommunicate();
			
		}
	}
	

	@Override
	public Match getItem(int position) {
		return matchList.get(position - 1);
	}

	private ArrayList<Match> matchList = new ArrayList<Match>();

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		ViewTag viewTag;
		if (convertView == null) {
			convertView = (View) LayoutInflater.from(context).inflate(
					R.layout.match_list_score_item, null);
			
			viewTag = new ViewTag();
			viewTag.tvLeagueName = (TextView) convertView.findViewById(R.id.tv_match_item_league_name);
			viewTag.tvHomeNumber = (TextView) convertView.findViewById(R.id.tv_match_item_home_number);
			viewTag.tvHomeName = (TextView) convertView.findViewById(R.id.tv_match_item_home_name);
			viewTag.tvHomeScore = (TextView) convertView.findViewById(R.id.tv_match_item_home_score);
			viewTag.tvAwayNumber = (TextView) convertView.findViewById(R.id.tv_match_item_away_number);
			viewTag.tvAwayName = (TextView) convertView.findViewById(R.id.tv_match_item_away_name);
			viewTag.tvAwayScore = (TextView) convertView.findViewById(R.id.tv_match_item_away_score);
			viewTag.tvMatchState = (TextView) convertView.findViewById(R.id.tv_match_item_match_state);
			viewTag.tvTimeState = (TextView) convertView.findViewById(R.id.tv_match_item_info_time_state);
			viewTag.tvTiming = (TextView)convertView.findViewById(R.id.tv_match_item_info_timing);
			viewTag.tvDaxiaoqiu = (TextView)convertView.findViewById(R.id.tv_match_item_info_peilv_daxiaoqiu);
			viewTag.tvBeginTime = (TextView)convertView.findViewById(R.id.tv_match_item_begin_time);
			viewTag.ivMark = (ImageButton) convertView.findViewById(R.id.ib_match_item_attention);
			viewTag.vgState = (ViewGroup)convertView.findViewById(R.id.ll_match_item_info_match_state_layout);
			convertView.setTag(viewTag);
		}
		viewTag = (ViewTag) convertView.getTag();

		// 设置比赛项比分相关内容
		Match matchInfo = matchList.get(position);
		EDebug.o("viewTag = "+viewTag.toString());
		viewTag.tvLeagueName.setText(matchInfo.getLeagueName().replaceAll("\\s*", "")+matchInfo.getStage());
		viewTag.tvBeginTime.setText(matchInfo.getMatchTime());

		viewTag.tvDaxiaoqiu.setText(matchInfo.getDaxiaoqiu());
		
		viewTag.tvHomeNumber.setText("["+matchInfo.getHomeNumber()+"]");
		viewTag.tvHomeName.setText(matchInfo.getHomeName());
		viewTag.tvHomeScore.setText(String.valueOf(matchInfo.getHomeScore()));
		
		viewTag.tvAwayNumber.setText("["+matchInfo.getAwayNumber()+"]");
		viewTag.tvAwayName.setText(matchInfo.getAwayName());
		viewTag.tvAwayScore.setText(String.valueOf(matchInfo.getAwayScore()));
		

		//Resources resources = context.getResources();

		switch (matchInfo.getShowState()) {
		case playing://正在进行的比赛
			
			viewTag.tvDaxiaoqiu.setVisibility(View.INVISIBLE);
			viewTag.vgState.setVisibility(View.VISIBLE);
			viewTag.tvTimeState.setText(matchInfo.getTimeState().toString());
			
			viewTag.tvMatchState.setText("");
			viewTag.tvMatchState.setBackgroundResource(R.drawable.icon_default_live_23x23);
			
			switch(matchInfo.getTimeState()){
			case firstHalf:
			case secondHalf:
				viewTag.tvTiming.setVisibility(View.VISIBLE);
				viewTag.tvTiming.setText(matchInfo.getTiming());
				break;
			case halfTime:
				viewTag.tvTiming.setVisibility(View.GONE);
				break;
			default:
				break;
			}
			//viewTag.tvTimeState.setTextColor(resources.getColor(R.color.match_state_right_now));
			viewTag.tvHomeScore.setBackgroundResource(R.drawable.img_default_score_ing);
			viewTag.tvAwayScore.setBackgroundResource(R.drawable.img_default_score_ing);
			viewTag.tvHomeScore.setText(String.valueOf(matchInfo.getHomeScore()));
			viewTag.tvAwayScore.setText(String.valueOf(matchInfo.getAwayScore()));
			break;
		case unplayed://未开赛的比赛
			viewTag.tvDaxiaoqiu.setVisibility(View.VISIBLE);
			viewTag.vgState.setVisibility(View.INVISIBLE);
			viewTag.tvDaxiaoqiu.setText(matchInfo.getDaxiaoqiu());
			
			viewTag.tvMatchState.setText(matchInfo.getMatchState().toString());
			if(matchInfo.getMatchState() == MatchState.changed){
				viewTag.tvMatchState.setTextColor(mResources.getColor(R.color.other));
			}else{
				viewTag.tvMatchState.setTextColor(mResources.getColor(R.color.unplayed));
			}
			
			viewTag.tvMatchState.setBackgroundColor(mResources.getColor(android.R.color.transparent));
		
			//viewTag.tvTimeState.setTextColor(resources.getColor(R.color.match_state_future));
			viewTag.tvHomeScore.setBackgroundResource(R.drawable.img_default_score_soon);
			viewTag.tvAwayScore.setBackgroundResource(R.drawable.img_default_score_soon);
			viewTag.tvHomeScore.setText("");
			viewTag.tvAwayScore.setText("");
			break;
		case over://已结束的比赛
			viewTag.tvDaxiaoqiu.setVisibility(View.VISIBLE);
			viewTag.vgState.setVisibility(View.INVISIBLE);
			viewTag.tvDaxiaoqiu.setText(matchInfo.getDaxiaoqiu());

			viewTag.tvMatchState.setText(matchInfo.getMatchState().toString());
			if(matchInfo.getMatchState() == MatchState.abort || matchInfo.getMatchState() == MatchState.undetermined ){
				viewTag.tvMatchState.setTextColor(mResources.getColor(R.color.other));
			}else{
				viewTag.tvMatchState.setTextColor(mResources.getColor(R.color.over));
			}
			viewTag.tvMatchState.setBackgroundColor(mResources.getColor(android.R.color.transparent));
			
			//viewTag.tvTimeState.setTextColor(Color.GRAY);
			viewTag.tvHomeScore.setBackgroundResource(R.drawable.img_default_score_end);
			viewTag.tvAwayScore.setBackgroundResource(R.drawable.img_default_score_end);
			viewTag.tvHomeScore.setText(String.valueOf(matchInfo.getHomeScore()));
			viewTag.tvAwayScore.setText(String.valueOf(matchInfo.getAwayScore()));
			break;
		default:
			break;
		}

		viewTag.ivMark.setImageResource(
				matchInfo.isMarked()
				? R.drawable.s_ib_star_marked
				: R.drawable.s_ib_star_unmarked);

		viewTag.ivMark.setOnClickListener(new OnMarkButtonClickListener(matchInfo));
		return convertView;
	}


	public ArrayList<Match> getList() {
		return matchList;
	}

	/**
	 * @title setList
	 * @description 设置数据列表
	 */
	public void setList(ArrayList<Match> list) {
		matchList = list;
		//updateStatistics();

	}

	class ViewTag {
		TextView tvLeagueName;
		TextView tvHomeNumber;
		TextView tvHomeName;
		TextView tvHomeScore;
		TextView tvAwayNumber;
		TextView tvAwayName;
		TextView tvAwayScore;
		TextView tvBeginTime;
		TextView tvMatchState;
		TextView tvTimeState;
		TextView tvTiming;
		TextView tvDaxiaoqiu;
		ViewGroup vgState;
		
		ImageButton ivMark;
	}

}
